package com.shwread.android.qysw.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.demo.common.ui.dialog.CustomAlertDialog.onSeparateItemClickListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.widget.touch_imageview.ExtendedViewPager;
import com.shwread.android.ui.widget.touch_imageview.TouchImageView;

import java.util.ArrayList;
import java.util.List;

import logic.constants.DefaultConsts;
import logic.util.FileUtil;
import logic.util.ImageLoaderUtil;
import logic.util.ImageUtil;


/**
 * @Description:图集详情页
 * @author: xuzhijun
 *          2015年1月17日 下午4:17:35
 */
public class NewInteractionAtlasSeeActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener
{
	public static final String  FROM_TYPE      = "fromType";
	public static final String  IMAGE_COUNT    = "image_count";
	private int                 fromType       = 0;
	private Context             context;
	private ExtendedViewPager   mViewPager;
	private TextView            mCount, mTitle, mIntro;
	private Button              mBackBtn;
	private List<String>        imgList;
	private RelativeLayout      titleLay, introLay;
	private DisplayImageOptions imageOptions;
	
	private int                 comeInPosition = 0;            //刚进来的position，从0开始
	private int                 totalNumber;                   //总条数
	private boolean             isShow         = true;         //是否加载完成
	                                                            
	private MyViewPagerAdapter  adapter;
	
	private CustomAlertDialog   alertDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.atlas_see_layout);
		context = this;
		alertDialog = new CustomAlertDialog(this);
		findView();
		initData();
		initListener();
	}
	
	private void initListener() {
		mViewPager.setOnPageChangeListener(new PageChangeListener());
		mBackBtn.setOnClickListener(this);
	}
	
	private void findView() {
		
		titleLay = (RelativeLayout) findViewById(R.id.atlas_see_title_lay);
		mBackBtn = (Button) findViewById(R.id.atlas_see_title_back);
		introLay = (RelativeLayout) findViewById(R.id.atlas_see_intro_lay);
		introLay.setVisibility(View.GONE);
		mCount = (TextView) findViewById(R.id.atlas_see_title_count);
		mTitle = (TextView) findViewById(R.id.atlas_see_title_name);
		mTitle.setVisibility(View.GONE);
		mIntro = (TextView) findViewById(R.id.atlas_see_intro);
		mIntro.setVisibility(View.GONE);
		mViewPager = (ExtendedViewPager) findViewById(R.id.atlas_see_vp);
	}
	
	private void initData() {
		
		imgList = new ArrayList<String>();
		adapter = new MyViewPagerAdapter();
		//图片加载的配置
		imageOptions = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565).cacheOnDisk(true).cacheInMemory(true).build();
		
		if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(DefaultConsts.FROM_TYPE))
		{
			int postion = 0;
			fromType = getIntent().getExtras().getInt(DefaultConsts.FROM_TYPE);
			imgList = getIntent().getExtras().getStringArrayList(DefaultConsts.NI_ATLASSEE_URL);
			if (getIntent().getExtras().containsKey(DefaultConsts.NI_POSITION))
			{
				postion = getIntent().getExtras().getInt(DefaultConsts.NI_POSITION);
			}
			
			totalNumber = imgList.size();
			mViewPager.setAdapter(adapter);
			mCount.setText(postion + 1 + "/" + totalNumber);
			mViewPager.setCurrentItem(postion);
		}
		
	}
	
	/**
	 * ViewPager滑动监听器
	 */
	private class PageChangeListener
	        implements
	        OnPageChangeListener
	{
		//		private int curCount = comeInPosition;
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}
		
		@Override
		public void onPageSelected(int arg0) {
			comeInPosition = arg0;
			mCount.setText((comeInPosition + 1) + "/" + totalNumber);
		}
	}
	
	class ViewHolder
	{
		LinearLayout   loading_lay, loadFail_lay;
		TouchImageView img;
	}
	
	class MyViewPagerAdapter
	        extends
	        PagerAdapter
	{
		
		@Override
		public int getCount() {
			return imgList.size();
		}
		
		@Override
		public View instantiateItem(ViewGroup container, final int position) {
			final ViewHolder holder;
			View view = null;
			holder = new ViewHolder();
			view = LayoutInflater.from(context).inflate(R.layout.atlas_see_item, mViewPager, false);
			holder.loading_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loading);
			holder.loadFail_lay = (LinearLayout) view.findViewById(R.id.atlas_see_item_loadfail);
			holder.img = (TouchImageView) view.findViewById(R.id.atlas_see_item_img);
			if (logic.util.Util.isNotEmpty(imgList.get(position)))
			{
				if (DefaultConsts.NI_FROM_WEBURL == fromType)
				{
					ImageLoaderUtil.loadWebUrl(imgList.get(position), holder.img, imageOptions, new MyImageLoadingListener(holder));
				}
				else if (DefaultConsts.NI_FROM_LOCALURL == fromType)
				{
					ImageLoaderUtil.loadLocalUrl(imgList.get(position), holder.img, imageOptions, new MyImageLoadingListener(holder));
				}
			}
			else
			{ //显示默认图片
				holder.img.setImageResource(R.drawable.atlas_see_item_loading_fail);
			}
			final String path = FileUtil.ImageSavePath();
			//			final String filename = new Md5FileNameGenerator().generate(imgList.get(position)) + ".PNG";
			//			final String dstPath = path + filename;
			holder.img.setOnClickListener(NewInteractionAtlasSeeActivity.this);
			holder.img.setOnLongClickListener(new OnLongClickListener()
			{
				
				@Override
				public boolean onLongClick(View v) {
					showWatchPictureAction(imgList.get(position), path);
					return true;
				}
			});
			holder.loading_lay.setOnClickListener(NewInteractionAtlasSeeActivity.this);
			
			//失败点击重新加载
			holder.loadFail_lay.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View v) {
					if (logic.util.Util.isNotEmpty(imgList.get(position)))
					{
						if (DefaultConsts.NI_FROM_WEBURL == fromType)
						{
							ImageLoaderUtil.loadWebUrl(imgList.get(position), holder.img, imageOptions, new MyImageLoadingListener(holder));
						}
						else if (DefaultConsts.NI_FROM_LOCALURL == fromType)
						{
							ImageLoaderUtil.loadLocalUrl(imgList.get(position), holder.img, imageOptions, new MyImageLoadingListener(holder));
						}
					}
					else
					{ //显示默认图片
						holder.img.setBackgroundResource(R.drawable.atlas_see_item_loading_fail);
					}
				}
			});
			
			container.addView(view);
			return view;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
	}
	
	// 图片长按
	protected void showWatchPictureAction(final String url, final String path) {
		if (alertDialog.isShowing())
		{
			alertDialog.dismiss();
			return;
		}
		alertDialog.clearData();
		String title = getString(R.string.save_to_device);
		alertDialog.addItem(title, new onSeparateItemClickListener()
		{
			@Override
			public void onClick() {
				ImageUtil.downImage(url, path, "", context);
				//				Thread thread = new Thread(new Runnable()
				//				{
				//					@Override
				//					public void run() {
				//						ImageUtil.downImage(url, path, "", context);
				//					}
				//				});
				//				thread.start();
//				try
//				{
//					ContentValues values = new ContentValues(2);
//					values.put(MediaStore.Images.Media.MIME_TYPE, C.MimeType.MIME_JPEG);
//					values.put(MediaStore.Images.Media.DATA, path);
//					getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//					Toast.makeText(NewInteractionAtlasSeeActivity.this, getString(R.string.picture_save_to), Toast.LENGTH_LONG).show();
//				}
//				catch (Exception e)
//				{
//					// may be java.lang.UnsupportedOperationException
//					Toast.makeText(NewInteractionAtlasSeeActivity.this, getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
//				}
			}
		});
		alertDialog.show();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.atlas_see_title_back:
				finish();
				break;
			case R.id.atlas_see_item_img:
				detailManager();
				break;
			case R.id.atlas_see_item_loading:
				detailManager();
				break;
		}
	}
	
	/**
	 * 管理上下内容的显示
	 */
	private void detailManager() {
		if (isShow)
		{
			hideDetail();
		}
		else
		{
			showDetail();
		}
	}
	
	private void hideDetail() {
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_out);
		titleLay.setAnimation(animationTop);
		animationTop.start();
		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_out);
		introLay.setAnimation(animationBottom);
		animationBottom.start();
		titleLay.setVisibility(View.GONE);
		introLay.setVisibility(View.GONE);
		isShow = false;
	}
	
	//显示图片细节，上下透明度
	private void showDetail() {
		titleLay.setVisibility(View.VISIBLE);
		//		introLay.setVisibility(View.VISIBLE);
		Animation animationTop = AnimationUtils.loadAnimation(this, R.anim.common_top_in);
		titleLay.setAnimation(animationTop);
		animationTop.start();
		//		Animation animationBottom = AnimationUtils.loadAnimation(this, R.anim.common_bottom_in);
		//		introLay.setAnimation(animationBottom);
		//		animationBottom.start();
		isShow = true;
	}
	
	/**
	 * 图片加载监听器
	 */
	class MyImageLoadingListener
	        implements
	        ImageLoadingListener
	{
		private ViewHolder holder;
		
		public MyImageLoadingListener(ViewHolder holder) {
			this.holder = holder;
		}
		
		@Override
		public void onLoadingCancelled(String arg0, View arg1) {
		}
		
		@Override
		public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
			updateLoadingView(1, holder);
		}
		
		@Override
		public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
			updateLoadingView(-1, holder);
		}
		
		@Override
		public void onLoadingStarted(String arg0, View arg1) {
			updateLoadingView(0, holder);
		}
		
	}
	
	/**
	 * @param state
	 *            0:加载中，1：加载完成，-1：加载失败
	 */
	private void updateLoadingView(int state, ViewHolder holder) {
		switch (state) {
			case 0:
				holder.loading_lay.setVisibility(View.VISIBLE);
				holder.loadFail_lay.setVisibility(View.GONE);
				holder.img.setVisibility(View.GONE);
				break;
			case 1:
				holder.loading_lay.setVisibility(View.GONE);
				holder.loadFail_lay.setVisibility(View.GONE);
				holder.img.setVisibility(View.VISIBLE);
				Animation animation = AnimationUtils.loadAnimation(context, R.anim.common_top_in);
				holder.img.setAnimation(animation);
				animation.start();
				break;
			case -1:
				holder.loading_lay.setVisibility(View.GONE);
				holder.loadFail_lay.setVisibility(View.VISIBLE);
				holder.img.setVisibility(View.GONE);
				break;
		}
	}
	
}
